const dayjs = require('dayjs')
const cloud = require('wx-server-sdk')
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
const config = require('../config')
const axios = require('axios')
// 给dayjs添加时区选项
dayjs.extend(utc);
dayjs.extend(timezone);

cloud.init({
    env: 'everyday-4gkd6una188bf952'
})
const db = cloud.database()

module.exports = async function (id) {
    if (!id) {
        return {
            msg: 'id不能为空'
        }
    }
    const remindResult = await db.collection('remind').where({
        _id: id
    }).get()
    const remindData = remindResult.data.length ? remindResult.data[0] : {}
    /**
     * 如果最近更新时间是今天，则直接取缓存
     */
    if (
        remindData.updateTime &&
        dayjs().tz('Asia/Shanghai').diff(dayjs(remindData.updateTime).format('YYYY-MM-DD'), 'day') === 0
    ) {
        return remindData
    }
    const {
        title,
        nickName,
        startDay,
        location,
        wordsOfLove
    } = remindData
    const values = await Promise.all(
        [
            // 获取天气信息
            axios.get(
                `https://devapi.qweather.com/v7/weather/3d?key=${config.weatherKey}&location=${location.id}`
            ),
            // 获取天气生活指数
            await axios.get(
                `https://devapi.qweather.com/v7/indices/1d?key=${config.weatherKey}&location=${location.id}&type=${config.type}`
            ),
            // 获取每日一句美好英语
            await axios.get(
                `http://api.tianapi.com/txapi/everyday/index?key=${config.tianXingKey}`
            )
        ]
    )
    const [weatherData, lifeData, oneData] = values
    // console.log(weatherData, lifeData, oneData)
    const {
        daily: weatherDataDaily
    } = weatherData.data;
    const {
        daily
    } = lifeData.data;
    const {
        newslist
    } = oneData.data
    const {
        imgurl
    } = Array.isArray(newslist) ? newslist[0] : ''
    // 计算日期
    const lovingDays = dayjs().tz('Asia/Shanghai').diff(
        startDay,
        'day'
    );
    const updateTime = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
    await db.collection('remind').doc(id).update({
        data: {
            weatherDataDaily: `${weatherDataDaily[0].tempMin}°C - ${weatherDataDaily[0].tempMax}°C`,
            daily,
            imgurl,
            lovingDays,
            updateTime
        }
    })
    return {
        weatherDataDaily: `${weatherDataDaily[0].tempMin}°C - ${weatherDataDaily[0].tempMax}°C`,
        daily,
        imgurl,
        lovingDays,
        wordsOfLove,
        title,
        nickName,
        updateTime
    }
}